package com.example.finger.dialog;

import android.app.Activity;
import android.content.Context;
import android.os.Bundle;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.TextView;

import com.example.finger.FingerHelper;
import com.example.finger.R;
import com.example.finger.SerialPortUtil;
import com.example.finger.bean.TaskSheet;
import com.google.gson.Gson;
import com.lyxmaster.lib.toasty.Toasty;
import com.lyxmaster.lib.util.DataConfig;

import java.util.ArrayList;
import java.util.List;
import java.util.Timer;
import java.util.TimerTask;

/**
 * Created by LYX on 2018/12/5.
 */

public class OpenTempLockDialog extends BaseDialog {
    private Context context;
    private List<String> list = new ArrayList<>();
    TaskSheet taskSheet;

    private TextView textViewTitile;
    private TextView textViewTip;
    private TextView textViewOpen;
    private TextView textViewClose;
    private TextView textViewCancel;
    private TextView textViewNum;
    private TextView textViewStauts;
    private TextView textViewSuogan;

    private int caozuo = 0;

    private int SHIFENG = 1;
    private int JIEFENG = 2;

    @Override
    public View createView(Context context, LayoutInflater inflater, ViewGroup container) {
        this.context = context;
        return inflater.inflate(R.layout.dialog_open_temp_lock, container, false);
    }

    public static OpenTempLockDialog getInstance(String title) {
        OpenTempLockDialog dialogFragment = new OpenTempLockDialog();
        dialogFragment.setCanceledBack(true);
        dialogFragment.setCanceledOnTouchOutside(true);

        Bundle args = new Bundle();
        args.putString("title", title);
        dialogFragment.setArguments(args);

        return dialogFragment;
    }

    @Override
    public void onActivityCreated(Bundle savedInstanceState) {
        super.onActivityCreated(savedInstanceState);

        taskSheet = new Gson().fromJson(getArguments().getString("title"), TaskSheet.class);

        String[] nums = taskSheet.getTask().getLocknum().split(" ");
        for (int j=0; j<nums.length; j++){
            list.add(nums[j]);
        }

        textViewTitile = getView().findViewById(R.id.tv_title);
        textViewTip = getView().findViewById(R.id.tv_tip);
        textViewOpen = getView().findViewById(R.id.tv_open);
        textViewClose = getView().findViewById(R.id.tv_close);
        textViewCancel = getView().findViewById(R.id.tv_cancle);
        textViewNum= getView().findViewById(R.id.tv_num);
        textViewStauts= getView().findViewById(R.id.tv_status);
        textViewSuogan = getView().findViewById(R.id.tv_suogan);

        textViewTitile.setText("编号：" + taskSheet.getTask().getNumber());

        textViewOpen.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                if(!list.contains(textViewNum.getText().toString())){
                    Toasty.error(getContext(), "此挂锁不在任务单内").show();
                    return;
                }
                try {
                    FingerHelper.getInStance().openLock(taskSheet,textViewNum.getText().toString());
                    caozuo = JIEFENG;
                } catch (Exception e) {
                    e.printStackTrace();
                    Toasty.error(getContext(), "开锁失败" + e.toString()).show();
                }
            }
        });

        textViewClose.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                if(!list.contains(textViewNum.getText().toString())){
                    Toasty.error(getContext(), "此挂锁不在任务单内").show();
                    return;
                }
                try {
                    FingerHelper.getInStance().closeLock(taskSheet,textViewNum.getText().toString());
                    caozuo = SHIFENG;
                } catch (Exception e) {
                    e.printStackTrace();
                    Toasty.error(getContext(), "关锁失败" + e.toString()).show();
                }
            }
        });

        textViewCancel.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                dismiss();
            }
        });

        SerialPortUtil.getInstance().setSCMDataReceiveListener(new SerialPortUtil.SCMDataReceiveListener() {
            @Override
            public void dataRecevie(final byte[] data) {
                ((Activity)(getContext())).runOnUiThread(new Runnable() {
                    @Override
                    public void run() {
                        try {
                            byte[] num = new byte[8];
                            System.arraycopy(data, 3, num, 0, 8);
                            textViewNum.setText(new String(num, "US-ASCII"));

                            char[] suogan = DataConfig.invertUsingFor(DataConfig.bytes2BinaryStr(new byte[]{data[23]}).toCharArray());
                            if(!(suogan[2] == '1')){
                                textViewSuogan.setText("关闭");
                            }else {
                                textViewSuogan.setText("打开");
                            }

                            if(suogan[1] == '1'){
                                textViewStauts.setText("开锁");
                                if(caozuo == SHIFENG){
                                    Toasty.success(getContext(), "开锁成功").show();
                                    caozuo = 0;
                                }

                            }else {
                                textViewStauts.setText("关锁");
                                if(caozuo == JIEFENG){
                                    Toasty.success(getContext(), "关锁成功").show();
                                    caozuo = 0;
                                }
                            }

                            resetTimer();
                        }
                        catch (Exception e) {
                            e.printStackTrace();
                        }
                    }
                });
            }
        });
    }

    private Timer timerBtRecv = new Timer();
    private TimerTask timerTaskBtRecv;
    private void resetTimer(){
        if(timerTaskBtRecv != null) timerTaskBtRecv.cancel();
        timerTaskBtRecv = new TimerTask() {
            @Override
            public void run() {
                try {
                    ((Activity)(getContext())).runOnUiThread(new Runnable() {
                        @Override
                        public void run() {
                            textViewNum.setText("");
                            textViewSuogan.setText("");
                            textViewStauts.setText("");
                        }
                    });
                }catch (Exception e){

                }

            }
        };
        timerBtRecv.schedule(timerTaskBtRecv, 3000);
    }

    @Override
    public void dismiss(){
        SerialPortUtil.getInstance().setSCMDataReceiveListener(null);
        if(timerTaskBtRecv != null) timerTaskBtRecv.cancel();
        super.dismiss();
    }
}
